//
//  StudyCourseQuestionsViewController.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/5/4.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "StudyCourseQuestionsViewController.h"
#import "ZJSCQusetionsSrectionView.h"
#import "ZJSCQusetionsTableViewCell.h"
#import "ZJSCQusetionsSrectionView.h"
#import "ZJRefurbish.h"
#import "SendCommentView.h"
#import <IQKeyboardManager.h>
#import "ZJSCFooterView.h"
#import "ZJShareManager.h"

#import "ZJSCQusetionsSrectionModel.h"
#define CellID @"ZJSCQusetionsTableViewCell"
#define SectionID  @"ZJSCQusetionsSrectionView"
@interface StudyCourseQuestionsViewController ()<UITableViewDelegate,UITableViewDataSource,ZJSCQusetionsSrectionViewDelegate,ZJSCQusetionsTableViewCellDelegate,SendCommentViewDelegate,ZJSCQusetionsSrectionViewCommentDelegate,ZJSCFooterViewDelegate>
{
    
    BOOL _isCourseComment;/**< 判断是否是课程评论、还是评论-评论 */
    UIView *_commentBGView;/** 评论页面背景View */
    ZJSCQusetionsSrectionModel *_commentSectionViewModel;/**< 记录评论SectionView的model */
}
/** tableView */
@property (nonatomic, strong) UITableView *tableView;
/** dataArray */
@property (nonatomic, strong) NSMutableArray *dataArray;
/**  分页  */
@property (assign, nonatomic) NSInteger  page;
/** 刷新页面 */
@property (nonatomic, strong) ZJRefurbish *refurbish;
/** 评论模块 */
@property (nonatomic, strong) SendCommentView *sendCommentView;
/** 评论输入框 */
@property (nonatomic, strong) ZJSCFooterView *footerView;
/** 分享 */
@property (nonatomic, strong) ZJShareManager *shareManager;
@end

@implementation StudyCourseQuestionsViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    if (self.block) {
        self.block();
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewBGGrayColor];
    __weak typeof(self) weakSelf = self;
    [self.refurbish headerToScollview:self.tableView Block:^{
        weakSelf.page = 1;
        [weakSelf netWorking_header];
    }];
    [self.refurbish footerToScollview:self.tableView Block:^{
        weakSelf.page ++;
        [weakSelf netWorking_footer];
    }];
    [self setupUI];
    [self.tableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
    
    [self comment_number];
}



- (void)setupUI{
    [self dataArray];
    self.titlelabel.text = @"评论详情";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.footerView];
    _commentBGView = [[UIView alloc] initWithFrame:self.view.bounds];
    _commentBGView.backgroundColor = [UIColor blackColor];
    _commentBGView.alpha = 0.2;
    _commentBGView.hidden = YES;
    UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_tapGester)];
    [_commentBGView addGestureRecognizer:tapGester];
    [self.view addSubview:_commentBGView];
    [self.view addSubview:self.sendCommentView];
}
#pragma mark - 网络请求
- (void)netWorking_header{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"STUDENTID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,
                           @"COURSEWAREID":self.model.ID,
                           @"PAGE_NUMBER":[NSString stringWithFormat:@"%ld",_page],
                           @"SHOW_NUMBER":@"10"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL listClassFAQ] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000" ]) {//获取成功
            weakSelf.dataArray = [[NSArray yy_modelArrayWithClass:[ZJSCQusetionsSrectionModel class] json:object[@"CLASS_FAQ"]] mutableCopy];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_header endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];

}

- (void)netWorking_footer{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"STUDENTID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,
                           @"COURSEWAREID":self.model.ID,
                           @"PAGE_NUMBER":[NSString stringWithFormat:@"%ld",_page],
                           @"SHOW_NUMBER":@"10"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL listClassFAQ] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000" ]) {//获取成功
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZJSCQusetionsSrectionModel class] json:object[@"CLASS_FAQ"]];
            [weakSelf.dataArray addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}


///查询评论总数
- (void)comment_number{
    [NetWorkingManager postWithUrlString:[NetWorkingURL countFAQ] Parameter:@{@"COURSEWAREID":self.model.ID} Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000" ]) {//获取成功
            self.footerView.number = [object objectForKey:@"TOTAL"];
        }
    } Fail:^(id object) {
        
    }];
}

#pragma mark - 键盘处理

- (void)action_tapGester{
    [self.view endEditing:YES];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    
    _commentBGView.hidden = NO;
    self.sendCommentView.hidden = NO;
    [self.view bringSubviewToFront:self.sendCommentView];
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - weakSelf.sendCommentView.height - curkeyBoardHeight, [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    _commentBGView.hidden = YES;
    self.sendCommentView.hidden = YES;
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
        
    }];
}

#pragma mark - 下部评论点击按钮
- (void)action_commentTextButton:(UIButton *)sender{
    _isCourseComment = YES;
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}

#pragma mark - ZJSCFooterViewDelegate(footerView 的点击) 协议方法
- (void)ZJSCFooterViewDelegate_commentClick{
    _isCourseComment = YES;
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}

- (void)ZJSCFooterViewDelegate_shareClick{
    ZJShareModel *model = [ZJShareModel new];
    model.title = @"测试";
    model.descr = @"微信分享";
    model.webpageUrl = @"www.baidu.com";
    model.thumImage = [UIImage imageNamed:@"img_default_s@2x"];
    self.shareManager.shareModel = model;
    [self.shareManager show];
}

#pragma mark - ZJSCQusetionsSrectionViewDelegate（评论SectionView） 协议方法
//(点赞或评论)sectionView上的按钮点击并网络请求完成
- (void)ZJSCQusetionsSrectionViewDelegate_operateSuccessToModel:(ZJSCQusetionsSrectionModel *)model section:(NSInteger)section{
    
    self.dataArray[section] = model;
}
#pragma mark - ZJSCQusetionsSrectionViewCommentDelegate(点击评论) 协议方法
//点击评论
- (void)ZJSCQusetionsSrectionViewDelegate_CommentClickToModel:(ZJSCQusetionsSrectionModel *)model{
    _commentSectionViewModel = model;
    _isCourseComment = NO;
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}
#pragma mark - ZJSCQusetionsTableViewCellDelegate （评论cell）协议方法
//Cell上的按钮被点击
- (void)ZJSCQusetionsTableViewCellDelegate_operateSuccessToModel:(ZJSCQusetionsCellModel *)model indexPatch:(NSIndexPath *)indexPatch{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[indexPatch.section];
    sectionModel.childModelArray[indexPatch.row] = model;
    
    self.dataArray[indexPatch.section] = sectionModel;
}

#pragma mark - SendCommentViewDelegate(发送评论) 协议方法
//发送评论
- (void)sendButtonClick{
    [self.view endEditing:YES];
    NSDictionary *dict = @{};
    if (_isCourseComment) {//是课程评论
        dict = @{@"USERID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//当前用户id
                 @"COURSEWAREID":self.model.ID,//课程id
                 @"ACCOUNTID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID,//账户id
                 @"CONTENT":self.sendCommentView.commentTextView.textView.text,//评论内容
                 @"VIDEOSTAMP":@(self.currTime),
                 @"UNITID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.CURRENTIDENTITY //机构id
                 };
    }else{//评论-评论
        dict = @{@"USERID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//当前用户id
                 @"COURSEWAREID":self.model.ID,//课程id
                 @"ACCOUNTID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID,//账户id
                 @"CONTENT":self.sendCommentView.commentTextView.textView.text,//评论内容
                 @"VIDEOSTAMP":@(self.currTime),
                 @"UNITID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.CURRENTIDENTITY, //机构id
                 @"FID":_commentSectionViewModel.ID
                 };
    }
    [self netWorkingCommentWithDict:dict];
        
    
}
//发送评论的网络请求
//评论
- (void)netWorkingCommentWithDict:(NSDictionary *)dict{
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    
    [NetWorkingManager postWithUrlString:[NetWorkingURL addClassFAQ] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//评论成功
            [YJProgressHUD showMsgWithoutView:@"评论成功"];
            weakSelf.page = 1;
            [weakSelf netWorking_header];
            [weakSelf comment_number];
        }else{
            
            [YJProgressHUD showMsgWithoutView:@"评论失败"];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"评论失败"];
    }];
    
}


#pragma mark - UITableView 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[section];
    
    return sectionModel.CHILD_CLASS_FAQ.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[indexPath.section];
    ZJSCQusetionsCellModel *cellModel = sectionModel.childModelArray[indexPath.row];
    
    ZJSCQusetionsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
    cell.model = cellModel;
    cell.indexPatch = indexPath;
    cell.delegate = self;
    if (indexPath.row == sectionModel.CHILD_CLASS_FAQ.count - 1) {
        cell.isLastCell = YES;
    }else{
        cell.isLastCell = NO;
    }
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[section];
    ZJSCQusetionsSrectionView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:SectionID];
    view.model = sectionModel;
    view.section = section;
    view.delegate = self;
    view.commentDelegate = self;
    return view;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[indexPath.section];
    ZJSCQusetionsCellModel *cellModel = sectionModel.childModelArray[indexPath.row];
    
    if (indexPath.row == sectionModel.CHILD_CLASS_FAQ.count - 1) {
        cellModel.isLastCell = YES;
    }else{
        cellModel.isLastCell = NO;
    }

    return cellModel.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    ZJSCQusetionsSrectionModel *sectionModel = self.dataArray[section];
    return sectionModel.sectionHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

#pragma mark - Setter


#pragma mark - Getters
- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight - 49) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 7.5 * [UIScreen zj_screenHScale])];
        view.backgroundColor = [UIColor viewBGGrayColor];
        _tableView.tableHeaderView = view;
        [_tableView  registerClass:[ZJSCQusetionsTableViewCell class] forCellReuseIdentifier: CellID];
        [_tableView registerClass:[ZJSCQusetionsSrectionView class] forHeaderFooterViewReuseIdentifier: SectionID];
        
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil){
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}

- (ZJRefurbish *)refurbish{
    if (_refurbish == nil){
        _refurbish = [ZJRefurbish new];
    }
    return _refurbish;
}

- (SendCommentView *)sendCommentView{
    if (_sendCommentView == nil){
        _sendCommentView = [[SendCommentView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], [UIScreen zj_screenHeight] * 0.2)];
        _sendCommentView.commentDelegate = self;
    }
    return _sendCommentView;
}

- (ZJSCFooterView *)footerView{
    if (_footerView == nil){
        _footerView = [[ZJSCFooterView alloc]initWithFrame:CGRectMake(0, self.view.height - 49, self.view.width, 49)];
        _footerView.backgroundColor = [UIColor whiteColor];
        _footerView.delegate = self;
        _footerView.isActivityIn = NO;
    }
    return _footerView;
}

- (ZJShareManager *)shareManager{
    if (_shareManager == nil){
        _shareManager = [[ZJShareManager alloc] init];
        
    }
    return _shareManager;
}

@end
